package cn.hlife.com.hlfhaemocyte.systemsetting.view;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.inuker.bluetooth.library.Constants;

import org.json.JSONException;
import org.json.JSONObject;

import cn.hlife.com.bluetooth20_connect.lib.BluetoothService;
import cn.hlife.com.hlfhaemocyte.MainActivity;
import cn.hlife.com.hlfhaemocyte.R;
import cn.hlife.com.hlfhaemocyte.bluetooth.BluetoothPrint;
import cn.hlife.com.hlfhaemocyte.bluetooth.ClientManager;
import cn.hlife.com.hlfhaemocyte.notify.Watcher;
import cn.hlife.com.hlfhaemocyte.utils.FragmentUtils;
import cn.hlife.com.hlfhaemocyte.utils.LogUtils;
import cn.hlife.com.hlfhaemocyte.utils.SharedPreferencesUtils;

/**
 * Created by Administrator on 2017/7/11.
 */

public class MacSetting extends Fragment  implements Watcher{
    private      EditText macBluetooth,  macPrint;
    private Button  retry_connect1,retry_connect2;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, @Nullable Bundle savedInstanceState) {
        View  view=inflater.inflate(R.layout.mac_setting,container,false);
        initView(view);
        return view;
    }
    public void initView( View  view) {
        macBluetooth=(EditText)view.findViewById(R.id.bluetooth_mac);
        macPrint=(EditText) view.findViewById(R.id.print_mac);
        view.findViewById(R.id.save_button).setOnClickListener(onClickListener);
        retry_connect2=(Button) view.findViewById(R.id.retry_connect2);
        retry_connect2 .setOnClickListener(onClickListener);
        retry_connect1=(Button) view.findViewById(R.id.retry_connect1);
        retry_connect1 .setOnClickListener(onClickListener);
//        view.findViewById(R.id.return_image).setOnClickListener(onClickListener);
        ((MainActivity)getActivity()).returnImageView.setVisibility(View.VISIBLE);
        ((MainActivity)getActivity()).returnImageView.setOnClickListener(onClickListener);
        ((MainActivity)getActivity()).getTransporter().addWatcher(this);
        readBluetoothMAC();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            ((MainActivity)getActivity()).returnImageView.setVisibility(View.VISIBLE);
//            readBluetoothMAC();
        }
    }

    public View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.save_button:
                    String  btmac=macBluetooth.getText().toString();
                    if(!checkValidity(btmac)){
                        return;
                    };
                    String pmac=macPrint.getText().toString();
                    if(!checkValidity(pmac)){
                        return;
                    };
                    saveMacAddress(btmac,pmac);
                    break;
                case R.id.return_image:
                    ((MainActivity)getActivity()).currentFragment = FragmentUtils.switchFragment
                            (getFragmentManager(), R.id.fragment_content, ((MainActivity)getActivity()).currentFragment, SettingFragment.class, null);
                    break;
                case R.id.retry_connect1:
                    String  btmac1=macBluetooth.getText().toString();
                    if(!checkValidity(btmac1)){
                        return;
                    };
                    JSONObject  jsonObject=new JSONObject();
                    try {
                        jsonObject.put("macBluetooth",macBluetooth.getText().toString().toUpperCase());
                        jsonObject.put("macPrint",macPrint.getText().toString().toUpperCase());
                        SharedPreferencesUtils.getInstance().saveBluetoothAddress(getActivity(), jsonObject.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    ((MainActivity)getActivity()).connBle(btmac1.toUpperCase());

                    break;
                case R.id.retry_connect2:
                    String pmac1=macPrint.getText().toString();
                    if(!checkValidity(pmac1)){
                        return;
                    };
                    JSONObject  jsonObject2=new JSONObject();
                    try {
                        jsonObject2.put("macBluetooth",macBluetooth.getText().toString().toUpperCase());
                        jsonObject2.put("macPrint",macPrint.getText().toString().toUpperCase());
                        SharedPreferencesUtils.getInstance().saveBluetoothAddress(getActivity(), jsonObject2.toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    ((MainActivity)getActivity()).connBluetoothPair(pmac1.toUpperCase());
                    break;
            }
        }
    };

    /**
     * 读取蓝牙的MAC的地址
     */
    public  void  readBluetoothMAC(){
        String macStr= SharedPreferencesUtils.getInstance().getBluetoothAddress(getActivity());
        try {
            if(!TextUtils.isEmpty(macStr)){
                JSONObject jsonObject=new JSONObject(macStr);
                macBluetooth.setText(jsonObject.getString("macBluetooth"));
                macPrint.setText(jsonObject.getString("macPrint"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }int status = 0;
        if(!TextUtils.isEmpty(macBluetooth.getText().toString())){
            status=ClientManager.getClient().getConnectStatus(macBluetooth.getText().toString());
        }
        if(status== Constants.STATUS_DEVICE_CONNECTED){
            retry_connect1.setClickable(false);
            retry_connect1.setText("已连接");
        }else{
            retry_connect1.setClickable(true);
            retry_connect1.setText("重新连接");
        }
        BluetoothService bluetoothService=BluetoothPrint.getInstance().getBluetoothService();
        if(bluetoothService!=null) {
            if (bluetoothService.getState() == BluetoothService.STATE_CONNECTED) {
                retry_connect2.setClickable(false);
                retry_connect2.setText("已连接");
            } else {
                retry_connect2.setClickable(true);
                retry_connect2.setText("重新连接");
            }
        }
    }

    /**
     * 保存蓝牙的mac地址
     * @param btmac
     * @param pmac
     */
    public  void saveMacAddress(String btmac,String  pmac){
        JSONObject  jsonObject=new JSONObject();
        try {
            jsonObject.put("macBluetooth",btmac.toUpperCase());
            jsonObject.put("macPrint",pmac.toUpperCase());
            SharedPreferencesUtils.getInstance().saveBluetoothAddress(getActivity(), jsonObject.toString());
            Toast.makeText(getActivity(),"MAC地址已保存",Toast.LENGTH_SHORT).show();
            ((MainActivity)getActivity()).currentFragment = FragmentUtils.switchFragment
                    (getFragmentManager(), R.id.fragment_content, ((MainActivity)getActivity()).currentFragment, SettingFragment.class, null);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    };
    /**
     * 检测mac的合法性
     * @param macString
     */
    public  boolean   checkValidity(String  macString){
        String matchsStr="[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}:[0-9A-F]{2}";
        if(!TextUtils.isEmpty(macString)){
            macString=macString.toUpperCase();
            boolean   res= macString.matches(matchsStr);
            if(!res){
                Toast.makeText(getActivity(),"MAC地址填写不合法",Toast.LENGTH_SHORT).show();
                return false;
            }
        }
//        else{
//            Toast.makeText(getActivity(),"MAC地址不能为空",Toast.LENGTH_SHORT).show();
//            return false;
//        }
        return true;
    }

    @Override
    public void update(final String mac, final boolean isState) {
        retry_connect1.post(new Runnable() {
            @Override
            public void run() {
                if(mac.equals(readBluetoothMAC("macPrint"))){

                    if(isState){
         ;             retry_connect2.setClickable(false);
                        retry_connect2.setText("已连接");
                    }else{
                        retry_connect2.setClickable(true);
                        retry_connect2.setText("重新连接");
                    }

                }else  if(mac.equals(readBluetoothMAC("macBluetooth"))){
                    if(isState){
                        retry_connect1.setClickable(false);
                        retry_connect1.setText("已连接");
                    }else{
                        retry_connect1.setClickable(true);
                        retry_connect1.setText("重新连接");
                    }
                }
            }
        });
    }

    /**
     * 读取蓝牙的MAC的地址
     */
    public String readBluetoothMAC(String key) {
        String macStr = SharedPreferencesUtils.getInstance().getBluetoothAddress(getContext());
        String macAddress = null;
        try {
            if (!TextUtils.isEmpty(macStr)) {
                JSONObject jsonObject = new JSONObject(macStr);
                macAddress = jsonObject.getString(key);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return macAddress;
    }
}
